import java.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;

public class Login extends HttpServlet
{
    public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException,IOException
    {
		doPost(request,response);
	}//doGet

    public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException,IOException
    {
		HttpSession session = request.getSession();
		RequestDispatcher dispatcher = null;
		String action = request.getParameter("eventAction");
		if( action.equals("confirmation") )
		{
			dispatcher = getServletContext().getRequestDispatcher("/jsp/ConfirmSignOut.jsp");
			dispatcher.forward(request,response);
		}
		else if( action.equals("signout") )
		{
			session = request.getSession(false);
			if( session != null )
			{
				session.invalidate();
				System.out.println("Session Invalidated");
				request.setAttribute("msg","Successfully LoggedOut..");
				dispatcher = getServletContext().getRequestDispatcher("/jsp/Login.jsp");
				dispatcher.forward(request,response);
			}
			else if( session == null)
			{
				dispatcher = getServletContext().getRequestDispatcher("/jsp/Login.jsp");
				dispatcher.forward(request,response);
			}
		}
		else if( action.equals("signin") )
		{
			try
			{
				String username = request.getParameter("username");
				String pwd = request.getParameter("password");

				Class.forName("com.mysql.jdbc.Driver").newInstance();
				Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/airtel","root","root");
				Statement stmt=con.createStatement();
				String qry = "select * from users where userName='"+username+"' and password='"+pwd+"'";
				System.out.println("+++++++"+qry);
				ResultSet rs = stmt.executeQuery(qry);

				if(rs.next())
				{
					session.setAttribute("username",username);
					session.setAttribute("password",pwd);
					if( rs.getBoolean(8) )
					{
						dispatcher = getServletContext().getRequestDispatcher("/jsp/AdminTemplate.jsp");
						dispatcher.forward(request,response);
					}
					else
					{
						dispatcher = getServletContext().getRequestDispatcher("/jsp/OperatorTemplate.jsp");
						dispatcher.forward(request,response);
					}
					System.out.println("Successful Login");
				}//if
				else
				{
					request.setAttribute("msg", new String("Authentication failed!! due to invalid username or password"));    
					dispatcher = getServletContext().getRequestDispatcher("/jsp/Login.jsp");
					dispatcher.forward(request,response);
				}
			}//try 
			catch(Exception e)
			{
				e.printStackTrace();
			}//catch
		}//if
	}//doPost
}//class